package com.czy.owner.ui.hotshop;

import android.content.Intent;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.czy.owner.R;
import com.czy.owner.adapter.SelectStoreAdapter;
import com.czy.owner.api.SelectStoreApi;
import com.czy.owner.callback.RecycleViewDivider;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.OwnerInfoModel;
import com.czy.owner.entity.SelectStoreModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.api.BaseResultEntity;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.net.utils.MyLoadView;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.utils.PhoneUtils;
import com.easyrecycleview.EasyRecyclerView;
import com.easyrecycleview.adapter.RecyclerArrayAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class ServiceStoreSearchActivity extends BaseActivity implements RecyclerArrayAdapter.OnLoadMoreListener , android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener{


    @BindView(R.id.et_store_search)
    EditText etStoreSearch;
    @BindView(R.id.img_clear)
    ImageView imgClear;
    @BindView(R.id.recyclerView)
    EasyRecyclerView recyclerView;
    private SelectStoreAdapter adapter;
    private int page = 1;
    private Handler handler = new Handler();
    private String session = "";
    private double gprsX; //经度
    private double gprsY;//纬度
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;
    private MyLoadView myLoadView;
    //标识，用于判断是否只显示一次定位信息和用户重新定位
    private boolean isFirstLoc = true;
    private String etContent;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_store_search;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        initLoc();
        myLoadView = new MyLoadView(this, "正在加载");
        recyclerView.setLayoutManager(new LinearLayoutManager(ServiceStoreSearchActivity.this));
        recyclerView.setAdapterWithProgress(adapter = new SelectStoreAdapter(ServiceStoreSearchActivity.this));
        recyclerView.addItemDecoration(new RecycleViewDivider(ServiceStoreSearchActivity.this, LinearLayoutManager.VERTICAL, R.drawable.shape_recyclerview_divider_decoration));

        recyclerView.setErrorView(R.layout.view_error_net);
        adapter.setMore(R.layout.view_more, ServiceStoreSearchActivity.this);
        adapter.setNoMore(R.layout.view_nomore);
        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener<SelectStoreModel>() {
            @Override
            public void onItemClick(View view,int position, SelectStoreModel o) {
                Intent intent = new Intent();
                intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, o);
                setResult(RESULT_OK,intent);
                finish();
            }
        });
        recyclerView.setRefreshListener(this);
        etStoreSearch.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {

                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                /*隐藏软键盘*/
                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(ServiceStoreSearchActivity.this.INPUT_METHOD_SERVICE);
                    if (inputMethodManager.isActive()) {
                        inputMethodManager.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                    }
                    etContent = etStoreSearch.getText().toString().trim();
                    if (etContent == null || TextUtils.isEmpty(etContent)) {
                        PhoneUtils.ShowToastMessage(ServiceStoreSearchActivity.this, "输入的内容不能为空");
                    } else {
                        page = 1;
                        getDataList(etContent);
                    }


                    return true;
                }
                return false;


            }
        });

        etStoreSearch.addTextChangedListener(new ServiceStoreSearchActivity.EditChangedListener());
    }

    @Override
    protected void updateViews() {

    }
    @Override
    public void onRefresh() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //刷新
                if (!PhoneUtils.isNetworkConnected(ServiceStoreSearchActivity.this)) {
                    adapter.pauseMore();
                    recyclerView.showError();
                    return;
                }
                page = 1;
                getDataList(etContent);

            }
        }, 1000);
    }
    @Override
    public void onLoadMore() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //刷新
                if (!PhoneUtils.isNetworkConnected(ServiceStoreSearchActivity.this)) {
                    adapter.pauseMore();
                    recyclerView.showError();
                    return;
                }
                page++;
                getDataList(etContent);

            }
        }, 1000);
    }


    public void getDataList(String ettext) {


        if (page == 1) {
            myLoadView.ShowLoadView();
            adapter.clear();
        }

        SelectStoreApi selectStoreApi = new SelectStoreApi(new HttpOnNextListener<List<SelectStoreModel>>() {
            @Override
            public void onNext(List<SelectStoreModel> list) {
                myLoadView.CancleLoadView();
                setSelectStoreList(list);

            }

            @Override
            public void onError(Throwable e) {
                myLoadView.CancleLoadView();
                super.onError(e);
                PhoneUtils.ShowToastMessage(ServiceStoreSearchActivity.this, e.getMessage());
            }

        }, this);
        selectStoreApi.setSession(UserHelper.getInstance().getSessionInfoModel(this).getSession());
        selectStoreApi.setGprsX(String.valueOf(gprsX));
        selectStoreApi.setGprsY(String.valueOf(gprsY));
        selectStoreApi.setPage(page + "");
        selectStoreApi.setSize("10");
        selectStoreApi.setGoodsId(getIntent().getStringExtra("goodsId"));
        selectStoreApi.setName(ettext);
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(selectStoreApi);

    }
    private void setSelectStoreList(List<SelectStoreModel> list) {
        if (page==1&&list.size()==0){
            recyclerView.setEmptyView(R.layout.view_empty_common);
            recyclerView.showEmpty();
        }
        if (list.size() < 10) {
            adapter.stopMore();
        }
        adapter.addAll(list);
    }

    //  定位回调监听事件
    AMapLocationListener mAMapLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //定位成功回调信息，设置相关消息
                    amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                    gprsX = amapLocation.getLongitude();//获取经度
                    gprsY = amapLocation.getLatitude();//获取纬度
                    amapLocation.getAccuracy();//获取精度信息
                    if (isFirstLoc) {

                        isFirstLoc = false;
                    }
                } else {
                    //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                    Log.e("qwe", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }
    };

    //定位初始化控件配置

    private void initLoc() {
        locationClient = new AMapLocationClient(ServiceStoreSearchActivity.this);
        //设置定位回调监听
        locationClient.setLocationListener(mAMapLocationListener);
        //初始化定位参数
        locationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        locationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        locationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        locationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        locationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        locationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        locationClient.setLocationOption(locationOption);
        //启动定位
        locationClient.startLocation();

    }




    class EditChangedListener implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (etStoreSearch.getText().toString().trim().length() > 0) {
                imgClear.setVisibility(View.VISIBLE);
            } else {
                imgClear.setVisibility(View.GONE);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (etStoreSearch.getText().toString().trim().length() > 0) {
                imgClear.setVisibility(View.VISIBLE);
            } else {
                imgClear.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != locationClient) {
            locationClient.stopLocation();
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
    }

    @OnClick({R.id.img_clear, R.id.tv_cancel})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_clear:
                etStoreSearch.setText("");
                break;
            case R.id.tv_cancel:
                finish();
                break;
        }
    }



}
